﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using IntelligentDecisioning.SharePoint.Actions;
using System.Web.UI;
using Microsoft.SharePoint;
using IntelligentDecisioning.SharePoint.Logging;

namespace IntelligentDecisioning.SharePoint.Controls
{
    /// <summary>
    /// Provides "first load" provisioning for sites e.g. Adding webparts
    ///  listviews etc to to pages.
    /// Runs an arbitary set of actions as provided by the extending class
    /// 
    /// TODO: refactor into a single control with actions located via SharePointServiceLocator
    /// </summary>
    public abstract class IDProvisioningControlBase: WebControl
    {
        #region Constructors

        public IDProvisioningControlBase()
        {
        }

        private ILog CreateFeatureInstallationLog(SPSite currentSite)
        {
            ILog provisioningLog = new FeatureInstallationLog(GetFeatureDisplayName(), GetFeatureId(), CurrentSite);
            return provisioningLog;
        }

        #endregion

        #region Get Actions

        public virtual List<ActionBase> GetActions()
        {
            return new List<ActionBase>();
        }

        #endregion

        #region Abstract methods implemented by the extending classes

        public abstract String GetKey();
        public abstract String GetFeatureDisplayName();
        public abstract Guid GetFeatureId();

        #endregion

        #region Public Properties

        public SPSite CurrentSite { get; private set; }
        public SPWeb CurrentWeb { get;  private set; }
        public SPFile CurrentPage { get; private set; }
        public ILog Log { get; private set; }

        #endregion

        #region Render

        protected override sealed void Render(HtmlTextWriter writer)
        {
            base.Render(writer);

            if (SPContext.Current != null)
            {
                using (CurrentSite = SPContext.Current.Site)
                {
                    // We create a feature installation log
                    // that allows us to tie up the provisioning actions
                    // with the provisioning steps taken when
                    // the feature was originally activiated
                    Log = CreateFeatureInstallationLog(CurrentSite);

                    using (CurrentWeb = SPContext.Current.Web)
                    {
                        // Run once for now
                        if (ProvisioningCodeNotRun(CurrentWeb))
                        {
                            CurrentWeb.AllowUnsafeUpdates = true;

                            foreach (ActionBase action in GetActions())
                            {
                                action.Provision(this);
                            }

                            SetProvisionedFlagToTrue(CurrentWeb);
                            CurrentWeb.AllowUnsafeUpdates = false;

                            // Force a refresh of the page to make our changes visible
                            writer.Write("<meta http-equiv=\"refresh\" content=\"0\">");
                        }
                    }
                }
            }
        }

        private bool ProvisioningCodeNotRun(SPWeb currentWeb)
        {
            String key = GetKey();
            bool notRun = true;

            if (currentWeb.AllProperties.ContainsKey(key))
            {
                notRun = false;
            }
            return notRun;
        }


        private void SetProvisionedFlagToTrue(SPWeb currentWeb)
        {
            currentWeb.Properties.Add(GetKey(), "true");
            currentWeb.Properties.Update();
          //  currentWeb.Update();
        }


        #endregion
    }
}
